import React, { useState, useEffect } from 'react'
import { Save, TestTube, CheckCircle, XCircle } from 'lucide-react'
import { kafkaApi } from '@/services/kafka'
import { settingsApi, KafkaConfig as KafkaConfigType } from '@/services/settings'
import { useKafkaStore } from '@/stores/kafkaStore'
import toast from 'react-hot-toast'

export default function KafkaConfig() {
  const { setConnectionStatus } = useKafkaStore()
  const [config, setConfig] = useState<KafkaConfigType>({
    bootstrap_servers: 'localhost:9092',
    security_protocol: 'PLAINTEXT',
    sasl_mechanism: 'PLAIN',
    sasl_username: '',
    sasl_password: '',
    api_version: 'auto'
  })

  const [testing, setTesting] = useState(false)
  const [saving, setSaving] = useState(false)
  const [testResult, setTestResult] = useState<{ success: boolean; message: string } | null>(null)

  // 加载配置
  useEffect(() => {
    const loadConfig = async () => {
      try {
        const configData = await settingsApi.getKafkaConfig()
        setConfig(configData)
        
        // 测试连接状态
        try {
          const result = await kafkaApi.testConnection()
          setConnectionStatus(result.success ? '已连接' : '连接失败', result.success)
        } catch (error) {
          setConnectionStatus('连接失败', false)
        }
      } catch (error) {
        console.error('从后端加载配置失败:', error)
        // 如果后端加载失败，尝试从localStorage加载
        const saved = localStorage.getItem('kafka_config')
        if (saved) {
          try {
            const parsedConfig = JSON.parse(saved)
            setConfig(parsedConfig)
          } catch (error) {
            console.error('加载配置失败:', error)
          }
        }
      }
    }

    loadConfig()
  }, [setConnectionStatus])

  const handleInputChange = (field: keyof KafkaConfigType, value: string) => {
    setConfig(prev => ({
      ...prev,
      [field]: value
    }))
    setTestResult(null) // 清除测试结果
  }

  const testConnection = async () => {
    setTesting(true)
    setTestResult(null)

    try {
      const result = await settingsApi.testKafkaConnection(config)
      setTestResult(result)
      
      if (result.success) {
        setConnectionStatus('已连接', true)
        toast.success('Kafka连接测试成功')
      } else {
        setConnectionStatus('连接失败', false)
        toast.error('Kafka连接测试失败')
      }
    } catch (error: any) {
      setTestResult({
        success: false,
        message: `连接失败: ${error.message || '网络错误'}`
      })
      setConnectionStatus('连接失败', false)
      toast.error('Kafka连接测试失败')
    } finally {
      setTesting(false)
    }
  }

  const saveKafkaConfig = async () => {
    setSaving(true)

    try {
      // 保存Kafka配置到后端Redis
      await settingsApi.saveKafkaConfig(config)

      // 同时保存到localStorage作为备份
      localStorage.setItem('kafka_config', JSON.stringify(config))

      toast.success('Kafka配置保存成功')
    } catch (error) {
      toast.error('Kafka配置保存失败')
    } finally {
      setSaving(false)
    }
  }

  return (
    <div className="card">
      <div className="card-header">
        <h2 className="card-title">Kafka连接配置</h2>
        <p className="card-description">
          配置Kafka集群连接信息，包括服务器地址、安全协议等
        </p>
      </div>
      <div className="card-content space-y-6">
        {/* 服务器地址 */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Bootstrap服务器 *
          </label>
          <input
            type="text"
            value={config.bootstrap_servers}
            onChange={(e) => handleInputChange('bootstrap_servers', e.target.value)}
            placeholder="localhost:9092"
            className="input"
          />
          <p className="text-xs text-gray-500 mt-1">
            Kafka集群的引导服务器地址，多个地址用逗号分隔
          </p>
        </div>

        {/* 安全协议 */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            安全协议
          </label>
          <select
            value={config.security_protocol}
            onChange={(e) => handleInputChange('security_protocol', e.target.value)}
            className="input"
          >
            <option value="PLAINTEXT">PLAINTEXT</option>
            <option value="SSL">SSL</option>
            <option value="SASL_PLAINTEXT">SASL_PLAINTEXT</option>
            <option value="SASL_SSL">SASL_SSL</option>
          </select>
        </div>

        {/* SASL配置 */}
        {(config.security_protocol === 'SASL_PLAINTEXT' || config.security_protocol === 'SASL_SSL') && (
          <>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                SASL机制
              </label>
              <select
                value={config.sasl_mechanism}
                onChange={(e) => handleInputChange('sasl_mechanism', e.target.value)}
                className="input"
              >
                <option value="PLAIN">PLAIN</option>
                <option value="SCRAM-SHA-256">SCRAM-SHA-256</option>
                <option value="SCRAM-SHA-512">SCRAM-SHA-512</option>
                <option value="GSSAPI">GSSAPI</option>
              </select>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  SASL用户名
                </label>
                <input
                  type="text"
                  value={config.sasl_username || ''}
                  onChange={(e) => handleInputChange('sasl_username', e.target.value)}
                  placeholder="输入SASL用户名"
                  className="input"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  SASL密码
                </label>
                <input
                  type="password"
                  value={config.sasl_password || ''}
                  onChange={(e) => handleInputChange('sasl_password', e.target.value)}
                  placeholder="输入SASL密码"
                  className="input"
                />
              </div>
            </div>
          </>
        )}

        {/* API版本 */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            API版本
          </label>
          <input
            type="text"
            value={config.api_version || 'auto'}
            onChange={(e) => handleInputChange('api_version', e.target.value)}
            placeholder="auto"
            className="input"
          />
          <p className="text-xs text-gray-500 mt-1">
            Kafka API版本，建议使用"auto"自动检测
          </p>
        </div>

        {/* 测试结果 */}
        {testResult && (
          <div className={`p-4 rounded-md ${
            testResult.success ? 'bg-green-50 border border-green-200' : 'bg-red-50 border border-red-200'
          }`}>
            <div className="flex items-center">
              {testResult.success ? (
                <CheckCircle className="h-5 w-5 text-green-500 mr-2" />
              ) : (
                <XCircle className="h-5 w-5 text-red-500 mr-2" />
              )}
              <span className={`text-sm font-medium ${
                testResult.success ? 'text-green-800' : 'text-red-800'
              }`}>
                {testResult.message}
              </span>
            </div>
          </div>
        )}

        {/* 操作按钮 */}
        <div className="flex space-x-3">
          <button
            onClick={testConnection}
            disabled={testing || !config.bootstrap_servers}
            className="btn-secondary"
          >
            <TestTube className={`h-4 w-4 mr-2 ${testing ? 'animate-spin' : ''}`} />
            {testing ? '测试中...' : '测试连接'}
          </button>

          <button
            onClick={saveKafkaConfig}
            disabled={saving || !config.bootstrap_servers}
            className="btn-primary"
          >
            <Save className={`h-4 w-4 mr-2 ${saving ? 'animate-spin' : ''}`} />
            {saving ? '保存中...' : '保存Kafka配置'}
          </button>
        </div>
      </div>
    </div>
  )
}
